import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:osc/common/MyTextStyle.dart';
import 'package:osc/data/repository/repository.dart';
import 'package:osc/common/osc_user_manager.dart';
import 'package:osc/models/entity/osc_author.dart';
import 'package:osc/models/entity/osc_base_list_entity.dart';
import 'package:osc/models/pop_result/pop_result.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/res/strings.dart';
import 'package:osc/ui/pages/account/login_page.dart';
import 'package:osc/ui/pages/user/user_profile.dart';
import 'package:osc/ui/widgets/no_data_widget.dart';
import 'package:osc/ui/widgets/user/osc_portraint_widget.dart';
import 'package:osc/ui/widgets/small_widgets.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

///黑名单
class Blacklist extends StatefulWidget {
  const Blacklist({Key key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new BlacklistState();
  }
}

class BlacklistState extends State<Blacklist>  {
  BlacklistState();

  HttpRepository httpRepository;
  String pageToken;
  int size = 0;
  int bannerCount = 3;
  bool isLoadedData = false;


  double paddingChildVertical = Dimens.gap_view_normal;


  List<OscAuthor> list;

  RefreshController controller = RefreshController(initialRefresh: true);
  ScrollController scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    httpRepository = HttpRepository();
  }

  @override
  void dispose() {
    super.dispose();
    controller.dispose();
    scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      controller: controller,
      onRefresh: refresh,
      onLoading: loadMore,
      enablePullUp: true,
      child: buildListView(),
    );
  }

  buildListView(){
    return ListView.separated(
      itemBuilder: (BuildContext context, int index) {
        if (size == 0) {
          return NoDataWidget();
        } else {
          return buildListItem(index);
        }
      },
      separatorBuilder: (BuildContext context, int index) {
        return SmallWidgets.buildLine();
      },
      itemCount: isLoadedData && size == 0? 1 : size,
    );
  }


  buildListItem(int index){
    OscAuthor item = list.elementAt(index);
    return Container(
      height: Dimens.view_item_height_biggest,
      width: ScreenUtil.getInstance().screenWidth,
      child: ListView(
        shrinkWrap: true,
        scrollDirection: Axis.horizontal,
        controller: scrollController,
        children: <Widget>[
          Container(
            width: ScreenUtil.getScreenW(context),
            child: buildUser(index),
          ),
          Container(
            width: 60,
            height: 40,
            alignment: Alignment.center,
            color: Colors.deepOrange,
            child: InkWell(
              onTap: (){
                reverserBlack(id: item.id, index: index);
              },
              child: Text("解除", style: MyTextStyle.LIST_TAG_BUTTON,),
            ),
          )
        ],
      ),
    );
  }

  buildUser(int index){
    OscAuthor item = list.elementAt(index);
    return GestureDetector(
      onTap: (){
        print("---ontap");
        jump2PageForResult(UserProfile(userId: item.id,));
      },
      child: Container(
        color: Colors.white,
        padding: EdgeInsets.symmetric(horizontal: Dimens.gap_activity_horizontal, vertical: Dimens.gap_view_normal),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            OscPortraitWidget(id: item.id, portraitImageUrl: item.portrait, size: Dimens.view_portrait_size_small,),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: Dimens.gap_view_normal),
              child: buildText(item.name, Colors.black, Dimens.font_sp14),
            ),
            Container(
              padding: EdgeInsets.symmetric(horizontal: Dimens.gap_view_smaller),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(Dimens.view_radius_size_smaller),
                border: Border.all(
                  color: Colors.green,
                ),
              ),
              child: buildText(item.identity.officialMember?"官方人员":"吃瓜群众", Colors.green, Dimens.font_sp10),
            ),
          ],
        ),
      ),
    );
  }


  buildText(String data, Color color, double fontSize) {
    return SmallWidgets.buildText(data, color, fontSize);
  }

  refresh() async{
    pageToken = null;
    list?.clear();
    await loadMore();
  }


  loadMore() async{
    isLoadedData = true;
//    scrollController.animateTo(0, duration: Duration(milliseconds: 300), curve: Curves.linear);
    List<OscAuthor> tempList;
    await httpRepository.getBlacklist(id: OscUserManager().userId, pageToken: pageToken).then((resp){
      if(resp != null && resp.success){
        OscBaseListResult<OscAuthor> result = resp.result;
        if(result != null){
          tempList = result.items;
          if(pageToken == null){
            list = tempList;
          } else {
            list.addAll(tempList);
          }
          size = list?.length??0;
          pageToken = result.nextPageToken;
          if(result.requestCount > result.responseCount){
            controller.loadNoData();
          } else {
            controller.loadComplete();
          }
        }
      }
    });

    if(mounted) {
      setState(() {
        controller.refreshCompleted();
      });
    }
  }

  Future<Null> reverserBlack({@required int id, @required int index}) async{
    await httpRepository.reverseBlack(id: id).then((resp) {
      if(resp.success){
        list.removeAt(index);
        size = list.length??0;
        showTips(resp.result?"已拉黑":"已解除拉黑");
      }
    });
    if (mounted) {
      setState(() {
      });
    }
  }

  jump2PageForResult(Widget page, {bool checkLogin = false}) {
    if(checkLogin){
      if(OscUserManager.getInstance().isLogin()){
        jumpToPageForResult(page);
      } else {
        jumpToPageForResult(LoginPage());
        showTips(StringIds.userNoLogin);
      }
    } else {
      jumpToPageForResult(page);
    }
  }
  jumpToPageForResult(Widget page) {
    NavigatorUtil.pushPageForResult<PopResult>(context, page).then((result) {
      if (result != null) {
        switch (result.id) {
          case PopResult.ID_LOGIN:
            break;
        }
      }
    });
  }

  showTips(String msg){
    PdUtil.showToast(msg: msg);
  }

}
